import base64, os
import uuid

from django.contrib.auth import login, authenticate
from django.shortcuts import render
from django_redis import get_redis_connection
from django.views import View
from django.http import JsonResponse
from apps.users.models import User
from apps.users.serializer.userinfo import UserSerializer
from celery_tasks.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code
from TenSq.settings.dev import logger
import re, json, random

# Create your views here.
from apps.users.models import User

"""
    接口:获取验证码

"""


class SMSCodeView(View):
    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_code')
        # 后端 避免 发送短信过于频繁
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁'})

        # - 3.生成随机6位码---random.randint()--存储redis数据库 mobile:6位码
        sms_code = '%06d' % random.randint(0, 99999)
        logger.info(sms_code)
        print('短信验证码:', sms_code)

        # 1.创建redis pipeline
        p1 = redis_conn.pipeline()
        # 2.将任务交给管道
        # 设置 发送短信过于频繁 标识
        p1.setex('send_flag_%s' % mobile, 60, 1)
        # 3.2 存储redis数据库 mobile:6位码
        p1.setex('sms_%s' % mobile, 300, sms_code)
        # 3.管道执行
        p1.execute()

        # - 4.celery--异步调用 --使用第三方 容联云 发短信
        from celery_tasks.sms.tasks import ccp_send_sms_code
        ccp_send_sms_code.delay(mobile, sms_code)

        # - 5.返回响应对象
        return JsonResponse({'code': 0, 'errmsg': '发送短信成功!'})


'''
    接口:登录
'''


# class LoginView(View):
#     def post(self, request):
#         # 1,接收参数,提取参数  json
#         json_dict = json.loads(request.body.decode())
#         username = json_dict.get('username')
#         password = json_dict.get('password')
#         user = authenticate(request, username=username, password=password)
#         if user is None:
#             return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误!'})
#
#         # 保持登录状态
#         login(request, user)
#
#         data = {
#             'id': user.id,
#             'username': user.username,
#             'mobile': user.mobile,
#             'token': '',
#             'avatar': user.avatar
#         }
#
#         return JsonResponse(data)


"""
    接口：注册
"""


class RegisterView(View):

    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        mobile = json_dict.get('mobile')
        sms_code = json_dict.get('sms_code')

        # 2.检验参数
        # if not all([username, password, mobile, sms_code]):
        #     return JsonResponse("缺少必传参数")
        #
        # # 检验手机号
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code':400,
        #                          'errmsg':'手机号格式有误'})
        #
        # if not re.match(r'^[a-zA-Z0-9]{6,16}$', password):
        #     return JsonResponse({'code':400,
        #                          'errmsg':'密码格式有误'})
        #
        # # 检验验证码
        # redis_conn = get_redis_connection('verify_code')
        # sms_code_server = redis_conn.get("sms_%s" % mobile)
        #
        # if not sms_code_server:
        #     return JsonResponse({'code':400,
        #                          'errmsg':'短信验证码过期'})
        # if sms_code != sms_code_server.decode():
        #     return JsonResponse({'code':400,
        #                          'errmsg':'输入的验证码有误'})

        # 3.存入数据库
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '数据保存失败'})

        # 4.保存状态
        login(request, user)
        # 5.返回结果
        data = {
            'id': user.id,
            'username': user.username,
            'mobile': user.mobile,
            'token': '',
            'avatar': user.avatar
        }

        return JsonResponse(data)


"===================================="
from django.http import JsonResponse, response, Http404
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.authentication import jwt_decode_handler

# from apps.headlines.pages import PageNum
from .models import User
# from serializers import UserSerializer, LabelsSerializer, LikeSerializer, UpdateLabelSerializer
from TenSq.settings.dev import BASE_DIR
from TenSq.utils.fastdfs.fastdfs_storage import FastDFSStorage


# from qa.models import Label


class PersonListView(APIView):
    # permission_classes = [IsAuthenticated]

    def get(self, request):
        person = User.objects.filter(id=request.user.id)
        # person = User.objects.all()

        serializer = UserSerializer(person, many=True)
        for i in serializer.data:
            print(dict(i))
            return JsonResponse(dict(i))

    def put(self, request):
        rcv_data = json.loads(request.body.decode())
        print(rcv_data)

        src = rcv_data['avatar']
        # if src:
        #     User.objects.filter(id=request.user.id).update(avatar=None)
        #     return JsonResponse({'errmsg': '请重试'})

        print(src)
        result = re.search("data:image/(?P<ext>.*?);base64,(?P<data>.*)", src, re.DOTALL)
        if result:
            '''判断是否第一次上传，个人档案头像只能上传一次'''
            ext = result.groupdict().get("ext")
            data = result.groupdict().get("data")

            # filepath = '/Users/mac/Desktop/'
            filepath = os.path.dirname(os.path.dirname(os.path.dirname(BASE_DIR)))

            # 2、base64解码
            img = base64.urlsafe_b64decode(data)
            filename = "{}.{}".format(uuid.uuid4(), ext)

            filepath_new = filepath + '/' + filename
            with open(filepath_new, "wb") as f:
                f.write(img)

            print(filepath_new)

            f = open(filepath_new, 'rb')
            ret = FastDFSStorage.save(self, name='name.jpg', content=f, max_length=None)
            url = FastDFSStorage.url(self, ret)

            print(url)

            person_change = User.objects.filter(id=request.user.id).update(
                realname=rcv_data['realname'],
                sex=rcv_data['sex'],
                birthday=rcv_data['birthday'],
                website=rcv_data['website'],
                mobile=rcv_data['mobile'],
                email=rcv_data['email'],
                city=rcv_data['city'],
                address=rcv_data['address'],
                avatar=url,
            )
        else:
            person_change = User.objects.filter(id=request.user.id).update(
                realname=rcv_data['realname'],
                sex=rcv_data['sex'],
                birthday=rcv_data['birthday'],
                website=rcv_data['website'],
                mobile=rcv_data['mobile'],
                email=rcv_data['email'],
                city=rcv_data['city'],
                address=rcv_data['address'],
                avatar=rcv_data['avatar']
            )

        person = User.objects.filter(id=request.user.id)
        serializer = UserSerializer(person, many=True)
        for i in serializer.data:
            print(dict(i))
            return JsonResponse(dict(i))


class PasswordView(View):
    '''修改密码'''

    def put(self, request):
        rcv_data = json.loads(request.body.decode())

        new_pwd = rcv_data.get('new_pwd')

        if not new_pwd:
            return JsonResponse({
                'message': '修改失败~',
                'type': 'error'
            })

        try:
            request.user.set_password(new_pwd)
            request.user.save()
        except Exception as e:
            return JsonResponse({'message': '修改失败~',
                                 'type': 'error'})
        return JsonResponse({
            'message': '修改成功',
            'type': 'success'
        })


class LikeView(APIView):
    '''添加好友关注和取消好友关注'''

    def post(self, request, pk):
        user_obj = User.objects.get(id=request.user.id)
        fans_obj = User.objects.get(id=pk)

        user_obj.fans.add(fans_obj)

        return JsonResponse({
            'success': True,
            'message': '关注成功'
        })

    def delete(self, request, pk):
        user_obj = User.objects.get(id=request.user.id)
        fans_obj = User.objects.get(id=pk)

        user_obj.fans.remove(fans_obj)

        return JsonResponse({
            'success': True,
            'message': '取消关注'
        })


class AvatarView(View):
    def post(self, request):
        '''头像上传'''

        rec_data = request.FILES.get('img')

        # FastDFSStorage.exists(data)

        ret = FastDFSStorage.save(self, name='name.jpg', content=rec_data, max_length=None)

        url = FastDFSStorage().url(ret)

        return JsonResponse({
            'imgurl': url
        })
